﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ones.ServiceNewsManagement;
using System.Transactions;
using Ones.ServiceHumanResourceManagement;

namespace Ones.Editorial.Approver
{
    public partial class NewsApproval : System.Web.UI.Page
    {
        #region Events
        private ServiceNewsManagement.ServiceNewsManagementClient srvNewsMngmt = null;
        private ServiceCategoryManagement.ServiceCategoryManagementClient srvCatMngmt = null;
        private ServiceHumanResourceManagement.ServiceHumanResourceManagementClient srvHrMngmt = null;
        string userAccount = string.Empty;
        int newsID = 0;

        enum processStatus
        {
            Approved,
            Edited,
            Posted,
            RejectedA,
            RejectedE
        }

        enum processDirection
        {
            Post,
            Reject
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            successfulMsg.Visible = false;
            failMsg.Visible = false;

            if (Session["user"] != null)
            {
                userAccount = Session["user"].ToString();
            }
            else { userAccount = "emp000004"; }

            if (!Page.IsPostBack)
            {
                this.BindDisplayedNews();
            }

        }

        protected void NewsUpdate_Confirm(object sender, CommandEventArgs e)
        {
            string alertNewsUpdateFailed = "alert('News cannot be updated due to invalid process status or incorrect owner!');";
            switch (e.CommandName.ToString())
            {
                case "cmdApprove":
                    if (this.ValidateNewUpdate())
                    {
                        if (this.EditNews("Approve"))
                        {
                            successfulMsg.Visible = true;
                            failMsg.Visible = false;
                        }
                        else
                        {
                            successfulMsg.Visible = false;
                            failMsg.Visible = true;
                        }
                    }
                    else
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", alertNewsUpdateFailed, true);
                    }

                    break;
                case "cmdUnpublish":

                    break;
                case "cmdRejectA":
                    if (this.ValidateNewUpdate())
                    {
                        if (this.EditNews("RejectA"))
                        {
                            successfulMsg.Visible = true;
                            failMsg.Visible = false;
                        }
                        else
                        {
                            successfulMsg.Visible = false;
                            failMsg.Visible = true;
                        }
                    }
                    else
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", alertNewsUpdateFailed, true);
                    }
                    break;
                case "cmdRemove":
                    if (this.RemoveNews())
                    {
                        successfulMsg.Visible = true;
                        failMsg.Visible = false;
                    }
                    else 
                    {
                        successfulMsg.Visible = false;
                        failMsg.Visible = true;
                    }
                    break;
                case "cmdCancel":
                    Response.Redirect("~/Editorial/Approver/NewsDisplay.aspx");
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region Methods
        private void BindDisplayedNews()
        {
            newsID = Convert.ToInt32(Session["newsId"]);

            srvNewsMngmt = new ServiceNewsManagement.ServiceNewsManagementClient("newsWsHttpBinding");
            srvCatMngmt = new ServiceCategoryManagement.ServiceCategoryManagementClient("catWsHttpBinding");

            Ones.ServiceNewsManagement.News n = new Ones.ServiceNewsManagement.News();

            n = srvNewsMngmt.RetrieveNewsByID(newsID);
            lblTitle.InnerHtml = n.newsTitle;

            var catResult = srvCatMngmt.searchCategoryById(n.catId);
            lblCategory.InnerText = catResult.catName;

            lblTime.InnerText = n.modificationDate.ToString();
            divIntro.InnerText = n.newsIntroduceText;
            divContent.InnerHtml = n.newsContent;
        }

        private bool ValidateNewUpdate()
        {
            srvNewsMngmt = new ServiceNewsManagementClient("newsWsHttpBinding");
            srvHrMngmt = new ServiceHumanResourceManagementClient("hrBasicHttpBinding");

            var n = srvNewsMngmt.RetrieveNewsByID(Convert.ToInt32(Session["newsId"]));

            IList<JobAssignment> jaSearhApprover = srvHrMngmt.searchDivisionByEmpId(userAccount);
            var jaApprover = jaSearhApprover.First<JobAssignment>();

            IList<JobAssignment> jaSearchAuthor = srvHrMngmt.searchDivisionByEmpId(n.author);
            var jaAuthor = jaSearchAuthor.First<JobAssignment>();

            if (n.processStatus.Equals("Edited") && (jaApprover.divId == jaAuthor.divId || jaApprover.divId == "div001"))
                return true;
            return false;
        }

        private bool EditNews(string action)
        {
            DateTime currentDate = System.DateTime.Now;
            String verComment = string.Empty;
            String editor = userAccount;

            using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    srvNewsMngmt = new ServiceNewsManagementClient("newsWsHttpBinding");

                    Ones.ServiceNewsManagement.News n = new Ones.ServiceNewsManagement.News();
                    Ones.ServiceNewsManagement.NewsVersion nv = new Ones.ServiceNewsManagement.NewsVersion();

                    var currentNews = srvNewsMngmt.RetrieveNewsByID(Convert.ToInt32(Session["newsId"]));
                    nv.verSender = userAccount;
                    nv.verComments = txtCommet.Value;

                    if (action.Equals("RejectA"))
                    {
                        bool result= srvNewsMngmt.ReviseNews("RejectA", currentNews, nv);
                        if (result)
                        {
                            trans.Complete();
                            return true;
                        }
                        return false;
                    }
                    else if (action.Equals("Approve"))
                    {
                        currentNews.publisher = userAccount;
                        bool result = srvNewsMngmt.ReviseNews("Approve", currentNews, nv);
                        if (result)
                        {
                            trans.Complete();
                            return true;
                        }
                        return false;
                    }
                    else { return false; }
                }
                catch (TransactionException ex)
                {
                    trans.Dispose();
                    return false;
                }
            }
        }

        private bool RemoveNews()
        {
            srvNewsMngmt = new ServiceNewsManagement.ServiceNewsManagementClient();

            if (ckboxARemovePer.Checked == false)
            {
                return srvNewsMngmt.RemoveNews(Convert.ToInt32(Session["newsId"]));
            }
            else
            {
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    try
                    {
                        bool result = srvNewsMngmt.DeleteNews(Convert.ToInt32(Session["newsId"]));
                        if (result)
                        {
                            trans.Complete();
                            return true;
                        }
                        return false;
                    }
                    catch (TransactionException ex)
                    {
                        trans.Dispose();
                        return false;
                    }
                }

            }

        }

        #endregion
    }
}